import 'package:appflutterhomeschool/model/questions_model.dart';
import 'package:appflutterhomeschool/res/styles.dart';
import 'package:appflutterhomeschool/ui/widgets/button_widget.dart';
import 'package:appflutterhomeschool/ui/widgets/my_app_bar.dart';
import 'package:appflutterhomeschool/ui/widgets/widgets.dart';
import 'package:appflutterhomeschool/utils/letter_display_utils.dart';
import 'package:appflutterhomeschool/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';

///用户： ninetailedfox
///时间： 2020/7/19
///邮箱： 1037438704@qq.com
///功能： 添加题型
class AddQuestionTypePage extends StatefulWidget {
  final int pageTag;
  final int getIndex;
  final QuestionsModel questionsModel;

  AddQuestionTypePage({this.pageTag, this.getIndex, this.questionsModel});

  @override
  _AddQuestionTypePageState createState() => _AddQuestionTypePageState();
}

class _AddQuestionTypePageState extends State<AddQuestionTypePage> {
  String title;
  TextEditingController textBody = TextEditingController();
  TextEditingController otherText = TextEditingController();

  List<Options> optionsList = [];

//  bool addOthers = false;
  bool childSwitch = true;
  String type = "";

  @override
  void initState() {
    super.initState();
    if (widget.questionsModel == null) {
      switch (widget.pageTag) {
        case 0:
          title = "单选题";
          type = "SC";
          optionsList.add(Options(type: "Normal"));
          optionsList.add(Options(type: "Normal"));
          break;
        case 1:
          type = "MC";
          optionsList.add(Options(type: "Normal"));
          optionsList.add(Options(type: "Normal"));
          title = "多选题";
          break;
        case 2:
          type = "C";
          title = "问答";
          break;
      }
    } else {
      title = widget.questionsModel.getStringType();
      textBody.text = widget.questionsModel.body;
      type = widget.questionsModel.questionType;
      widget.questionsModel.options.forEach((element) {
        if (element.type == "Normal") {
          element.itemText.text = element.option;
          optionsList.add(element);
        } else {
//          addOthers = true;
//          otherText.text = element.option;
        }
      });
      childSwitch = widget.questionsModel.isAnswer == "T";
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        appBar: MyAppBar2(title: title),
        body: Stack(
          children: <Widget>[
            Positioned(
              left: 0,
              right: 0,
              top: 0,
              bottom: ScreenUtil().setWidth(115),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    EditWidget(
                        hintText: "点击编辑题目名称", textEditingController: textBody),
                    Visibility(
                      child: ListView.builder(
                          itemCount: optionsList.length,
                          physics: NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (context, index) {
                            return Container(
                              padding: EdgeInsets.only(
                                  right: ScreenUtil().setWidth(43)),
                              child: Row(children: [
                                Expanded(
                                    child: EditWidget(
                                  hintText: '点击编辑选项',
                                  textEditingController:
                                      optionsList[index].itemText,
                                )),
                                Visibility(
                                  visible: optionsList.length != 1,
                                  child: GestureDetector(
                                    child: Icon(Icons.do_not_disturb_on,
                                        color: Colors.grey),
                                    onTap: () {
                                      optionsList.removeAt(index);
                                      setState(() {});
                                    },
                                  ),
                                )
                              ]),
                            );
                          }),
                      visible: widget.pageTag != 2 && widget.pageTag != 3,
                    ),
//                    _others(),
                    Visibility(
                      visible: type != "C",
                      child: Row(
                        children: <Widget>[
                          _rowWidget("添加选项", onTap: () {
                            optionsList.add(Options(type: "Normal"));
                            setState(() {});
                          }),
//                          Visibility(
//                            visible: !addOthers,
//                            child: _rowWidget("添加其他", onTap: () {
//                              setState(() {
//                                addOthers = true;
//                              });
//                            }),
//                          )
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.all(ScreenUtil().setWidth(43)),
                      child: Row(
                        children: [
                          Text("必答题", style: TextStyles.textGray37),
                          Spacer(),
                          GestureDetector(
                            onTap: () {
                              childSwitch = !childSwitch;
                              Fluttertoast.showToast(msg: "$childSwitch");

                              setState(() {});
                            },
                            child: Image.asset(Utils.getImgPath(!childSwitch
                                ? "gabu_kaiguan_guan"
                                : 'gabu_kaiguan_kai')),
                          ),
                        ],
                      ),
                    ),
//                    AcademicItemTitle(
//                      academicVisible:
//                          widget.pageTag == 1 || widget.pageTag == 3,
//                      title: "最少答题数",
//                      titleStyle: TextStyles.textDark37,
//                      contentStyle: TextStyles.textDark37,
//                      content: "已完成",
//                      visible: true,
//                      padding: EdgeInsets.all(ScreenUtil().setWidth(43)),
//                    ),
//                    AcademicItemTitle(
//                      academicVisible: widget.pageTag == 1,
//                      title: "最多答题数",
//                      titleStyle: TextStyles.textDark37,
//                      content: "已完成",
//                      visible: true,
//                      contentStyle: TextStyles.textDark37,
//                      padding: EdgeInsets.all(ScreenUtil().setWidth(43)),
//                    )
                  ],
                ),
              ),
            ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: ButtonWidget().rectangleButtonWidget(
                  buttonName: "发布",
                  onPressed: () {
                    if (textBody.text == "") {
                      Fluttertoast.showToast(msg: "请输入标题");
                      return;
                    }
                    int itemTextContext = 0;
                    if (optionsList.length != 0) {
                      for (int i = 0; i < optionsList.length; i++) {
                        if (optionsList[i].itemText.text == null) {
                          itemTextContext++;
                        } else {
                          optionsList[i].order =
                              LetterDisplayUtils.getIndexLetter(i);
                          optionsList[i].option = optionsList[i].itemText.text;
                        }
                      }
                      if (itemTextContext != 0) {
                        Fluttertoast.showToast(msg: "选项不能为空");
                        return;
                      }
                    }
//                    if (addOthers) {
//                      if (otherText.text == "") {
//                        Fluttertoast.showToast(msg: "其他不能为空");
//                        return;
//                      } else {
//                        optionsList.add(
//                            Options(option: otherText.text, type: "Other"));
//                      }
//                    }

                    QuestionsModel questionsModel = QuestionsModel();
                    questionsModel.options = optionsList;
                    questionsModel.body = textBody.text;
                    //类型：String  必有字段  备注：是否必答（是：T；否:F）
                    questionsModel.isAnswer = childSwitch ?"T":"F";
                    //题号
                    questionsModel.questionOrder = widget.questionsModel == null
                        ? "${widget.getIndex + 1}"
                        : widget.questionsModel.questionOrder;
                    questionsModel.questionType = type;
                    Navigator.pop(context, questionsModel.toJson());
                  }),
            )
          ],
        ),
      ),
    );
  }

  Widget _rowWidget(String content, {GestureTapCallback onTap}) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.all(ScreenUtil().setWidth(43)),
        child: Row(
          children: [
            Icon(Icons.add, color: Colors.blue),
            Text(
              content ?? "添加选项",
              style: TextStyles.textBlue36,
            ),
          ],
        ),
      ),
      onTap: onTap,
    );
  }

  //其他组件
  Widget _others() {
    return Visibility(
//      visible: addOthers,
      child: Container(
        padding: EdgeInsets.only(
            left: ScreenUtil().setWidth(43), right: ScreenUtil().setWidth(43)),
        child: Row(children: [
          Text("其他", style: TextStyles.textGray37),
          Container(
            width: 150,
            child: EditWidget(
              hintText: '',
              inputBorder: true,
              textEditingController: otherText,
            ),
          ),
          Spacer(),
          GestureDetector(
            child: Icon(Icons.do_not_disturb_on, color: Colors.grey),
            onTap: () {
              setState(() {
//                addOthers = false;
              });
            },
          )
        ]),
      ),
    );
  }
}
